package cricket

import (
	"log"
	"longmen/server/config/global"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/api/v5/sports/cricket/cricket_behaviour"
	"longmen/server/internal/services/nami/config"
	"longmen/server/internal/services/nami/utils/restyclient"
	"longmen/server/pkg/db/mysql/models/models_sports"
)

func SyncCompPoint() {
	resp := cricket_behaviour.CompPoint{}
	err := restyclient.GetUrlAndBindRecords(config.CRCompPoint, &resp)
	if err != nil {
		global2.Log.Error("获取更新列表失败: ", err)
		return
	}

	if len(resp.Results.Tables) > 0 {
		for _, v := range resp.Results.Tables {
			for _, ch := range v.Rows {
				log.Println("resp.Results.Tables.Rows Count:", len(v.Rows))
				log.Println("resp.Results.Tables.Rows:", v.Rows)
				var tempTeam models_sports.CricketTeam
				err := global.Sport().Model(&tempTeam).Where("id=?", ch.TeamID).First(&tempTeam).Error
				if err != nil {
					global2.Log.Error("球队信息不存在，更新数据失败: ", err)
					continue
				}
				r := &models_sports.CricketPoint{
					ID:       ch.TeamID,
					StageID:  v.StageID,
					Name:     v.Name,
					TeamID:   ch.TeamID,
					Position: ch.Position,
					Points:   ch.Points,
					Total:    ch.Total,
					Win:      ch.Win,
					Draw:     ch.Draw,
					Loss:     ch.Loss,
				}
				rows := global2.Sport().Model(&models_sports.CricketPoint{}).Where("id=?", r.ID).Updates(&r).RowsAffected
				log.Println("team_id rows:", rows)
				if rows == 0 {
					err := global2.Sport().Model(&models_sports.CricketPoint{}).Create(&r).Error
					log.Println("team_id create error:", err)
					if err != nil {
						global2.Log.Error("球队更新数据失败: ", err)
						continue
					}
				}
			}
		}
	}
}
